package com.pubinfo.passbook.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.mashape.unirest.request.GetRequest;
import com.pubinfo.passbook.common.entity.TPassbook;
import com.pubinfo.passbook.common.mapper.TFileInfoMapper;
import com.pubinfo.passbook.common.mapper.TSourcePassbookMapper;
import com.pubinfo.passbook.data.service.DownLoadPDFService;
import com.pubinfo.passbook.data.service.TFileInfoService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

@Service
@Slf4j
public class DownLoadPdfServiceImpl implements DownLoadPDFService {

    @Value("${file.uploadFolder}")
    private String filePath;
    @Autowired
    TFileInfoService tFileInfoService;
    @Autowired
    TSourcePassbookMapper tSourcePassbookMapper;
    @Autowired
    TFileInfoMapper tFileInfoMapper;

    @Override
    public void downLoadPDFByEInvoiceId(String eInvoiceId) {
        TPassbook passbook = tSourcePassbookMapper.selectByEInvoiceId(eInvoiceId);
        downLoad(passbook);
    }

    @Override
    public void downLoadPDFByPassbook(List<TPassbook> passbookList) {
        //过滤没有下载的票据
        List<TPassbook> destList = new ArrayList<TPassbook>(passbookList);

        destList.removeIf(t -> (t.getIsDownload()));
        if (CollectionUtils.isEmpty(destList)) {
            return;
        }
        destList.stream().forEach(t -> {
            downLoad(t);
        });
    }

    @Override
    public void downLoadPDF() {
        List<TPassbook> passbookList = tSourcePassbookMapper.selectNotDownload();
        for (TPassbook passbook : passbookList) {
            downLoad(passbook);
        }
        tSourcePassbookMapper.updateIsDownload();
    }

    @SneakyThrows
    private void downLoad(TPassbook passbook) {
        if (passbook.getEinvoicePdf() != null && CollectionUtils.isEmpty(tFileInfoMapper.selectByPassbookId(passbook.getEInvoiceId()))) {
            GetRequest getRequest = sendGet(passbook.getEinvoicePdf());
            String s = getRequest.asString().getHeaders().toString();
            Pattern r = compile("filename=\".+\"");
            Matcher m = r.matcher(s);
            if (m.find()) {
                String fileName = m.group(0);
                fileName = fileName.replace("filename=", "").replace("\"", "");
                MultipartFile file = new MockMultipartFile(fileName, fileName, ContentType.APPLICATION_OCTET_STREAM.toString(), getRequest.asBinary().getBody());
                tFileInfoService.uploadFile("system", file, passbook.getIssueDate() + "_" + fileName, passbook.getEInvoiceId(), createPath(passbook));
                log.info(passbook.getEInvoiceId() + "PDF下载成功");
            } else {
                log.info(passbook.getEInvoiceId() + "PDF下载失败，该电子票据PDF文件未生成");
            }
        }
    }

    private String createPath(TPassbook tPassbook) {
        return filePath + "passbook/" + tPassbook.getIssueDate() + "/";
    }

    private GetRequest sendGet(String url) throws UnirestException {
//        Unirest.setTimeouts(0, 0);
        GetRequest response = Unirest.get(url)
                .header("Authorization", "Basic enBpdXNlcjE6WnBpYXBwbEAxMjM0")
                .header("User-Agent", "apifox/1.0.0 (https://www.apifox.cn)");
        Unirest.clearDefaultHeaders();
        return response;
    }
}
